package com.lagou.xm.io.config;

import com.lagou.xm.io.Resources;
import com.lagou.xm.io.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * @param in
     * @Description 解析config.xml文件
     * @author XM, Email is huangwei_xm@163.com
     * @since 2020/9/24 22:22
     */
    public Configuration parseConfig(InputStream in) {
        // 通过dom4j读取配置文件
        Document document = null;
        try {
            document = new SAXReader().read(in);
        } catch (DocumentException e) {
            throw new RuntimeException("config.xml解析失败：" + e.getMessage());
        }
        // 获取根节点<configuration>
        Element rootElement = document.getRootElement();
        // 获取数据源配置
        List<Element> propertyList = rootElement.selectNodes("//property");
        // 创建配置信息
        Properties properties = new Properties();
        for (Element element : propertyList) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }
        // 创建数据库链接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        // 数据库驱动
        try {
            comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        } catch (PropertyVetoException e) {
            throw new RuntimeException("数据库连接驱动加载失败：" + e.getMessage());
        }
        // 数据库数据库链接地址
        comboPooledDataSource.setJdbcUrl(properties.get("jdbcUrl").toString());
        // 数据库账户
        comboPooledDataSource.setUser(properties.get("username").toString());
        // 数据库密码
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);
        // 解析Mapper
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        try {
            for (Element element : mapperList) {
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
                InputStream resource = Resources.getResourceAsStream(element.attributeValue("resource"));
                xmlMapperBuilder.parse(resource);
            }
        } catch (DocumentException e) {
            throw new RuntimeException("Mapper.xml解析失败：" + e.getMessage());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Class For Name is Error.error msg:" + e.getMessage());
        }
        return configuration;
    }
}
